package io.renren.modules.job.task;
import io.renren.common.utils.*;
import io.renren.modules.noc.entity.NocMemberEntity;
import io.renren.modules.noc.entity.NocTemplateEntity;
import io.renren.modules.noc.service.NocMemberService;
import io.renren.modules.noc.service.NocTemplateService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 朋友圈数据
 */
@Component("weixinTask")
public class WeixinTask implements ITask {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private MemberQRCodeUtil memberQRCodeUtil;

    @Value("${ercode.pre}")
    private String _pre;

    @Override
    public void run(String params){
        //params 参数格式 tid=1&appId=xx&secret=xx&startTime=2019-04-01&endTime=2019-05-11&campaignId=
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        String tid = UriUtil.getParamByUrl(params,"tid");
        String startTime = UriUtil.getParamByUrl(params,"startTime");
        String endTime = sd.format(new Date());
        String allCampaignId = UriUtil.getParamByUrl(params,"campaignId");
        String appid = UriUtil.getParamByUrl(params,"appId");
        String appsecret = UriUtil.getParamByUrl(params,"secret");
        String md = UriUtil.getParamByUrl(params,"md");
        //NocTemplateEntity template = nocTemplateService.getById(tid);
        //String appid = template.getPappid();
        //String appsecret  = template.getPappsecret();
        HttpClient client = new HttpClient();
        String param = "&appid="+appid+"&secret="+appsecret;
        String accessToken = client.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential",param);
        String strArray[] = accessToken.split("\"");
        String accessToken3 = strArray[3];
        String[] campaignIdList = new String[10];
        if(allCampaignId!=null){
            campaignIdList= allCampaignId.split(",");
        }
        //此三个参数不能为空
        if(StringUtils.isNotEmpty(tid)&&StringUtils.isNotEmpty(startTime)
                &&StringUtils.isNotEmpty(endTime)){

            for(String campaignId:campaignIdList){
                saveData(tid,startTime,endTime,accessToken3,campaignId,md);
            }

        }
    }

    //保存数据
    public void saveData(String tid,String startTime,String endTime,String accessToken,String campaignId,String md){
        String json = pullClues(accessToken,startTime,endTime,campaignId,"1","10");
        JSONObject obj = JSONObject.fromObject(json);
        String status = obj.getString("errcode");
        if("0".equals(status)){
            String data = obj.getString("data");
            JSONObject lastObj = JSONObject.fromObject(data);
            String lastData = lastObj.getString("list");
            sendMsgAndSaveData(lastData,tid,md);
            String pageInfo = lastObj.getString("page_info");
            JSONObject page = JSONObject.fromObject(pageInfo);
            int number = page.getInt("total_page");
            if(number>1){
                for(int i =1;i<number;i++){
                    json = pullClues(accessToken,startTime,endTime,campaignId,(1+i)+"","10");
                    obj = JSONObject.fromObject(json);
                    String s = obj.getString("errcode");
                    if("0".equals(s)){
                        data = obj.getString("data");
                        lastObj = JSONObject.fromObject(data);
                        lastData = lastObj.getString("list");
                        sendMsgAndSaveData(lastData,tid,md);
                    }
                }
            }

        }
    }

    public void sendMsgAndSaveData(String lastData,String tid,String md){
        try{
            JSONArray array = JSONArray.fromObject(lastData);
            for (int i = 0; i < array.size(); i++){
                JSONObject item = (JSONObject) array.get(i);
                String leadsInfo = item.getString("leads_info");
                JSONArray item1 = JSONArray.fromObject(leadsInfo);
                String mobile = JSONObject.fromObject(item1.get(0)).get("value").toString();
                String createTime = JSONObject.fromObject(item1.get(1)).get("value").toString();
                String name = JSONObject.fromObject(item1.get(2)).get("value").toString();
                String huiyibmb_cusname = "";
                String huiyibmb_canhren = "";
                if(tid.equals("7")){
                    huiyibmb_canhren = JSONObject.fromObject(item1.get(3)).get("value").toString();
                }else{
                    huiyibmb_cusname = JSONObject.fromObject(item1.get(3)).get("value").toString();
                    huiyibmb_canhren = JSONObject.fromObject(item1.get(4)).get("value").toString();
                }


                Map<String, Object> p = new HashMap<>();
                p.put("col1", mobile);
                p.put("tid", tid);
                List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(p);
                if (list != null && list.size() > 0) {
                    //todo 用户已经存在
                }else{
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    NocMemberEntity member = new NocMemberEntity();
                    member.setCol1(mobile);
                    member.setTid(Integer.parseInt(tid));
                    member.setCol2(huiyibmb_cusname);
                    member.setCol13(huiyibmb_canhren);
                    member.setCol3(name);
                    member.setCreateTime(sdf.parse(createTime));
                    member.setCol15("1");
                    member.setLy("friends");
                    member.setCol10(md);
                    String ercode = memberQRCodeUtil.getMemberQRCode(_pre);
                    if(StringUtils.isNotEmpty(ercode)){
                        member.setCol20(ercode);
                    }else{
                        member.setCol20(_pre+"000001");
                    }
                    nocMemberService.save(member);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 调用微信接口
     * @param startTime
     * @param endTime
     * @param page
     * @param pageSize
     * @return
     */
    public String pullClues(String accessToken, String startTime, String endTime,String campaignId,String page,String pageSize){
        String params = "access_token="+accessToken+"&version=v1.0"+"&date_range={\"start_date\":\""+startTime+
                "\",\"end_date\":\""+endTime+"\"}"+"&filtering=[{\"field\":\"campaign_id\",\"operator\":\"EQUALS\",\"values\":[\""+campaignId+"\"]}]"+
                "&page="+page+"&page_size="+pageSize;
        String surl = "https://api.weixin.qq.com/marketing/wechat_ad_leads/get"+params;
        HttpClient client = new HttpClient();
        String str = client.sendGet("https://api.weixin.qq.com/marketing/wechat_ad_leads/get" , params);
        System.out.println(str);
        return str;
    }


}
